import { arrayRemove, PaginatorPlugin } from "@datorama/akita";
import { filter, switchMap, tap } from "rxjs/operators";

import { TwMessagesQuery, TwMessagesStore, makeStore, TwMessageEntity } from "@/state/twMessageEntity/store";
import messageService from "@/services/messageService";
import { TwMsgRevokeReq } from "@/models/request/msgReq";
import { MessageItem } from "@/models/Message";

export class TwMessagesFacade {
  constructor(private groupId: string, private store: TwMessagesStore, private query: TwMessagesQuery, public paginator: PaginatorPlugin<TwMessageEntity>) {
  }

  pagination$ = this.paginator.pageChanges.pipe(
    switchMap((pageNum) => {
      const reqFn = () => messageService.getTuwenMsgSvc(this.groupId, pageNum, 10);
      return this.paginator.getPage(reqFn);
    }),
  )

  //TODO 主播撤回消息（2分钟内可以撤回）
  revokeMessage = (req: TwMsgRevokeReq) => {
    return messageService.revokeTwMsgSvc(req)
  }
 
  prevPage = () => {
    this.paginator.prevPage();
  }

  nextPage = () => {
    this.paginator.nextPage();
  }

  refreshPage = () => {
    this.paginator.refreshCurrentPage();
  }

  lastPage = () => {
    this.paginator.setLastPage();
  }

  //销毁store实例，释放内存
  destroy = () => {
    this.paginator.destroy();
    this.store.destroy();
  }
}

export const makeFacade = (groupId: string): TwMessagesFacade => {
  const [store, query, paginator] = makeStore();

  return new TwMessagesFacade(groupId, store, query, paginator);
}